package com.xhtt.modules.inspection.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xhtt.common.exception.RRException;
import com.xhtt.common.exception.RRExceptionEnum;
import com.xhtt.common.file.FileInfoModel;
import com.xhtt.common.utils.*;
import com.xhtt.modules.inspection.dao.InsTaskStepPointMapper;
import com.xhtt.modules.inspection.entity.*;
import com.xhtt.modules.inspection.enums.PointTypeEnum;
import com.xhtt.modules.inspection.enums.SignEnum;
import com.xhtt.modules.inspection.service.*;
import lombok.extern.slf4j.Slf4j;
import lombok.val;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 巡检任务-巡检记录
 * </p>
 *
 * @author xj
 * @since 2019-01-29
 */
@Service
@Slf4j
public class InsTaskStepPointServiceImpl extends ServiceImpl<InsTaskStepPointMapper, InsTaskStepPoint> implements IInsTaskStepPointService {

    @Autowired
    private IInsPointSubitemService insPointSubitemService;

    @Autowired
    private IInsPointService insPointService;

    @Autowired
    private IInsTaskService insTaskService;

    @Autowired
    private IInsTaskStepService insTaskStepService;

    @Override
    public PageUtils queryPageByStepId(Map<String, Object> params) {

        Page<InsTaskStepPoint> page = new Query<InsTaskStepPoint>(params).getPage();

        IPage iPage = baseMapper
                .selectPage(page, new LambdaQueryWrapper<InsTaskStepPoint>()
                        .eq(InsTaskStepPoint::getTaskStepId, params.get("taskStepId")));

        List<InsTaskStepPoint> insTaskStepPoints = iPage.getRecords();

        List<InsPointSubitem> insPointSubs = new ArrayList<>();
        for (InsTaskStepPoint e : insTaskStepPoints) {
            Integer pointSubId = e.getPointSubitemId();
            // 检查内容
            InsPointSubitem insPointSubitem = insPointSubitemService.getAllById(pointSubId);
            if (StringUtils.isNotEmpty(e.getPhotoFile())) {
                try {
                    insPointSubitem.setFileInfoModels(JSON.parseArray(e.getPhotoFile(), FileInfoModel.class));
                } catch (Exception ex) {
                    log.error("照片转换失败 照片字符串={}", e.getPhotoFile());
                    ex.printStackTrace();
                }
            }
            if (insPointSubitem != null) {
                BeanUtils.copyProperties(e, insPointSubitem);
                Integer pointId = insPointSubitem.getPointId();
                insPointSubitem.setDatetime(e.getCreateTime());
                insPointSubitem.setIsSign(EnumUtils.getMsgByCode(SignEnum.class, e.getIsSign()).getMsg());
                // 检点
                InsPoint insPoint = insPointService.getAllById(pointId);
                if (insPoint != null) {
                    insPointSubitem.setPointType(EnumUtils.getMsgByCode(PointTypeEnum.class, insPoint.getPointType()).getMsg());
                    insPointSubitem.setDeviceName(insPoint.getDeviceName());
                }
                insPointSubitem.setRealVal(e.getValue());
                insPointSubs.add(insPointSubitem);
            }
        }
        iPage.setRecords(insPointSubs);
        return new PageUtils(iPage);
    }

    @Override
    public void exportExcel(HttpServletResponse response, Map<String, Object> params) {

        Integer taskStepId = Integer.parseInt(params.get("taskStepId").toString());

        InsTaskStep insTaskStep = insTaskStepService.getById(taskStepId);

        if (insTaskStep != null) {
            InsTask insTask = insTaskService.getAllById(insTaskStep.getTaskId());

            ExportExcel exportExcel = new ExportExcel();

            params.put("limit", String.valueOf(this.count(new LambdaQueryWrapper<InsTaskStepPoint>().eq(InsTaskStepPoint::getTaskStepId, params.get("taskStepId")))));

            PageUtils pageUtils = this.queryPageByStepId(params);
            List<InsPointSubitem> list = (List<InsPointSubitem>) pageUtils.getList();
            list.forEach(e -> {
                String sign = e.getIsSign();
                if (StringUtils.isEmpty(sign)) {
                    sign = DateUtils.df.format(e.getCreateTime());
                }
                e.setIsSign(sign);
            });

            String fileName = insTask.getTaskName() + "_记录详情";
            String sheetName = "sheet1";
            String[] headers = {"检点类型", "设备/检查项名称", "巡检内容", "实时值", "状态描述", "巡检时间", "备注"};
            String[] columns = {"pointType", "deviceName", "name", "realVal", "statusDescription", "isSign", "memo"};
            try {
                exportExcel.exportExcel(fileName, sheetName, headers, columns, list, response);
            } catch (Exception e) {
                e.printStackTrace();
                throw new RRException(RRExceptionEnum.EXPORT_FAIL);
            }
        }


    }
}
